<?php

namespace Xrfg\Api\Trading\Spot\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Xrfg\Core\Trading\Spot\Models\Order;
use Xrfg\Core\Trading\Spot\Models\Trade;
use Xrfg\Api\Trading\Spot\Requests\TradeIndexRequest;
use Xrfg\Api\Trading\Spot\Resources\TradesResource;

class TradeController extends Controller
{
    /**
     * 成交记录.
     *
     * @param TradeIndexRequest $request
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(TradeIndexRequest $request)
    {
        $symbol = $request->query('symbol');
        $orderType = $request->query('order_type'); // 订单类型：LIMIT- 限价单 MARKET-市价单
        $side = $request->query('side');
        $startTime = $request->query('start_time');
        $endTime = $request->query('end_time');
        $time = $request->query('time'); // 1-最近7天 2-7天到3个月
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;

        $userId = Auth::id();
        $trades = Trade::query()
            ->where(function (Builder $query) use ($userId) {
                return $query->where('buy_user_id', $userId)
                    ->orWhere('sell_user_id', $userId);
            })
            ->when($symbol, function (Builder $query) use ($symbol) {
                return $query->where('symbol', $symbol);
            })
            ->when(in_array(strtoupper($orderType), ['LIMIT', 'MARKET']), function (Builder $query) use ($orderType, $userId) { // 订单类型：LIMIT- 限价单 MARKET-市价单
                $allTrades = Trade::where('buy_user_id', $userId)
                    ->orWhere('sell_user_id', $userId)
                    ->get();
                $allowIds = [];
                foreach ($allTrades as $allTrade) {
                    if (Order::find(max($allTrade->buy_order_id , $allTrade->sell_order_id))->type == strtoupper($orderType)) {
                        array_push($allowIds, $allTrade->id);
                    }
                }
                return $query->whereIn('id', $allowIds);
            })
            ->when($startTime, function (Builder $query) use ($startTime) {
                return $query->where('created_at', '>=', $startTime);
            })
            ->when($endTime, function (Builder $query) use ($endTime) {
                return $query->where('created_at', '<=', $endTime);
            })
            ->when($time == 1, function (Builder $query) { // 1-最近7天
                return $query->where('created_at', '>=', now()->subDays(7));
            })
            ->when($time == 2, function (Builder $query) { // 2-7天到3个月
                return $query->where('created_at', '>=', now()->subDays(30))->where('created_at', '<', now()->subDays(7));
            })
            ->when($side, function (Builder $query) use ($side) {
                return $query->where('side', $side);
            })
            ->orderByDesc('id')
            ->paginate($perPage)
            ->appends($request->only(['symbol', 'type', 'start_time', 'end_time', 'per_page']));

        return TradesResource::collection($trades);
    }
}
